/**
 * Created by 红岩 on 2015/9/13.
 */
$(function () {
    //加载消息
    var initmessage = function (receiveuid) {
        var url = "/initmessage"
        $.post(url, {receiveuid: receiveuid}, function (res) {
            if (res != "0") {
                var div_content = $("#div_content");
                div_content.html("")
                var data = eval("(" + res + ")")
                var uid = $("#uid").val();
                for (var i = 0; i < data.length; i++) {
                    var da = data[i];
                    var htmlbase;
                    var portrait = "<img src='" + da.sendport + "' width='20' height='20'/>";
                    if (uid == da.senduid) {
                        htmlbase = '<div class="panel panel-default" id="data' + da.mid + '" style="text-align: right"><div class="panel-heading">'
                            + da.mtime + ' ' + da.sendnick + portrait + '</div><div class="panel-body">' + da.mcontent + '</p> </div></div>';
                    } else {
                        htmlbase = '<div class="panel panel-default" id="data' + da.mid + '"><div class="panel-heading">'
                            + portrait + da.sendnick + ' ' + da.mtime + '</div><div class="panel-body">' + da.mcontent + '</p> </div></div>';
                    }
                    div_content.append(htmlbase)
                }
                //设置窗口滚动条在最低部
                //var h = $(document).height() - $(window).height();
                //$("#div_content").scrollIntoView();
                //设置div滚动条在最低部
                $('#div_content').scrollTop($('#div_content')[0].scrollHeight);
            } else if (res == "-1") {
                window.location.href = "/userlogin"
            }

        })
    }

    //获取用户
    var genUser = function () {
        var url = "/getuser"
        $.post(url, {}, function (res) {
            var data = eval("(" + res + ")")
            var receive = $("#receiveuid");
            var userList = $("#user_list");
            for (var i = 0; i < data.length; i++) {
                var da = data[i];
                var option = $("<option></option>");
                option.attr({"value": da.uid}).html(da.unick)
                receive.append(option)
                //用户列表
                var portrait = "<img src='" + da.uportrait + "' width='20' height='20'/>";
                var html = "<a href=\"#\" id=\"" + da.uid + "\" nick=\"" + da.unick + "\" class=\"list-group-item\">" + portrait + "&nbsp;" + da.unick + "</a>";
                userList.append(html)
            }
            addUserListClick()
        });
    }
    var addUserListClick = function () {
        var a = $("#user_list a");
        a.click(function () {
            var o = $(this);
            var id = o.attr("id");
            $("#nick").html(o.attr("nick") + "&nbsp;")
            $("#receiveuid").val(id)
            initmessage(id)
            $("#msg_window").show()
        })
    }
    $("#logpage").click(function () {
        window.location.href = "/userlogin"
    });
    genUser();//获取用户
    $("body").keyup(function (event) {
        if (event.keyCode == 13 || (event.keyCode == 17 && event.keyCode == 13)) {
            $("#form").submit()
        }
    });
    //----------------websocket------------------------
    var conn;
    var msg = $("#content");
    var div_content = $("#div_content");

    function appendLog(msg) {
        var htmlbase;
        var data = eval("(" + msg + ")");//msgtype,uid,nick,time,portrait,content
        if (data.msgtype == 2) {
            htmlbase = '<div class="panel panel-default" id="data">'
                + '<div class="panel-heading"></div><div class="panel-body">'
                + data.content + '</p> </div></div>';
            $("#send").attr("disabled", "disabled")
            var url = "/unsession"
            $.get(url, {}, function (data) {
                alert(data)
                window.location.href = "/userlogin"
            })
        } else {
            var style = "style=\"text-align: right\""
            var portrait = "<img src='" + data.portrait + "' width='20' height='20'/>";
            if (data.msgtype == 1) {
                htmlbase = '<div class="panel panel-default" id="data" ' + style + '>'
                    + '<div class="panel-heading">' + data.time + ' ' + data.nick + portrait + '</div><div class="panel-body">'
                    + data.content + '</p> </div></div>';
            } else {
                htmlbase = '<div class="panel panel-default" id="data">'
                    + '<div class="panel-heading">' + portrait + data.nick + ' ' + data.time + '</div><div class="panel-body">'
                    + data.content + '</p> </div></div>';
                if ($('#chatAudio').length > 0) {
                    $('#chatAudio')[0].play();
                }
            }
        }
        div_content.append(htmlbase)
        //设置div滚动条在最低部
        $('#div_content').scrollTop($('#div_content')[0].scrollHeight);
        msg.focus()
    }

    $("#closesound").click(function () {
        var o = $(this);
        var t = o.attr("t");
        if (t == 0) {
            $('#chatAudio').remove()
            o.attr("t", "1");
            o.val("打开提示音")
        } else if (t == 1) {
            addsound()
            o.attr("t", "0");
            o.val("关闭提示音")
        }
    });
    $("#form").submit(function () {
        if (!conn) {
            return false;
        }
        var msgVal = $.trim(msg.val());
        if (msgVal == "") {
            return false;
        }
        //选择的接收者id
        var uid = $("#receiveuid").val()
        if (uid == "") {
            return false;
        }
        var sendData = "{\"uids\":[" + uid + "],\"data\":\"" + msgVal + "\"}";
        //发送消息
        conn.send(sendData);
        msg.val("");

        return false
    });
    if (window["WebSocket"]) {
        //创建连接
        conn = new WebSocket("ws://10.105.99.99:8999/ws");
        conn.onclose = function (evt) {
            appendLog("连接关闭.")
        }
        //接收消息
        conn.onmessage = function (evt) {
            appendLog(evt.data)
        }
    } else {
        appendLog($("<div><b>浏览器不支持WebSocket.</b></div>"))
    }
    //----------------websocket------------------------
    var addsound = function () {
        $('<audio id="chatAudio"><source src="sound/notify.ogg" type="audio/ogg"><source src="sound/notify.mp3" type="audio/mpeg"><source src="sound/notify.wav" type="audio/wav"></audio>').appendTo('body');
    }
    addsound()
})